"""
客户端
"""
from socket import *
from  multiprocessing import Process

ADDR = ("127.0.0.1",12122)

def login(sock):
    while True:
        name = input("请输入昵称：")
        if len(name) < 2:
            continue
        msg = "LOGIN\t" + name
        sock.sendto(msg.encode(),ADDR)
        result,addr = sock.recvfrom(128)
        if result == b'OK':
            print("您已进入聊天室")
            return name
        else:
            print("该昵称已存在")

def recv_msg(sock):
    while True:
        msg,addr = sock.recvfrom(1024*1024)
        print("\n" + msg.decode() + "\n>>",end="")

def send_msg(sock,name):
    while True:
        try:
            content = input(">>")
        except:
            content = "exit"
        if content == "exit":
            msg = "EXIT\t" + name
            sock.sendto(msg.encode(), ADDR)
            return
        msg = "CHAT\t%s\t%s"%(name,content)
        sock.sendto(msg.encode(), ADDR)

def chat(sock,name):
    p = Process(target=recv_msg, args=(sock,),daemon=True)
    p.start()
    send_msg(sock,name)


def main():
    sock = socket(AF_INET,SOCK_DGRAM)
    # sock.bind(("0.0.0.0", 53535))
    name = login(sock)
    chat(sock,name)

if __name__ == '__main__':
    main()

